<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '借书申请' : '新建借书申请'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: isDraft || flowContext.isStartNode,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的图书借阅申请` }),
      submit: submitAudit,
      finish: () => submitAudit({ beforeSend }),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <template #toolbar-right> </template>
    <FormHolder ref="form" label-width="110px" :disabled="isDisabled" :model="entity">
      <FormItemGroup block-title="基本信息">
        <FormInput v-model="entity.cardNumber" prop="cardNumber" label="卡号" required max-length="255" />
        <FormInput v-model="entity.orderNo" prop="orderNo" disabled label="借阅单号" max-length="255" />
        <FormInputUser
          :id.sync="entity.borrowerId"
          :name.sync="entity.borrower"
          prop="borrower"
          label="借阅人姓名"
          required
          max-length="255"
          @input="setUser" />
        <FormInput :value="entity.useUnitName" disabled prop="useUnitName" label="使用单位" />
        <FormTextarea v-model="entity.remark" prop="remark" label="借阅说明" max-length="800" />
      </FormItemGroup>
      <FormItemGroup enabled :gutter="0" block-title="借阅清单">
        <FormTable
          :key="entity.status"
          v-model="entity.books"
          required
          label="书籍"
          hide-label
          prefix-pick
          :disabled="isDisabled"
          label-width="0"
          prop="books"
          :columns="columns"
          @add-row="pickerVisible = true">
          <template #status="{ row }">
            <ConfirmButton
              v-if="entity.status === 2 && row.status === 2"
              message="你确定要归还书籍吗?"
              type="primary"
              :disabled="false"
              @click="returnBook(row)">
              归还
            </ConfirmButton>
          </template>
        </FormTable>
      </FormItemGroup>
    </FormHolder>
    <BookPicker v-if="pickerVisible" :visible.sync="pickerVisible" @confirm="confirm" />
  </FormView>
</template>

<script>
  import { save, checkBooksStatus, create, load, update, returnBook } from './api'
  import flowForm from '@/vue/mixin/flow-form'
  import { bookBorrowStatus } from '@/module/library/book/dictionary'
  import BookPicker from '@/module/library/book/BookPicker.vue'

  export default {
    name: 'BookApplyForm',
    components: { BookPicker },
    docType: 'bookApply',
    relativeViewId: 'BookApplyView',
    mixins: [flowForm],
    data() {
      return {
        pickerVisible: false,
        entity: {
          id: null,
          cardNumber: null,
          borrowerId: null,
          borrower: null,
          remark: null,
          orderNo: null,
          borrowDateTime: null,
          returnDateTime: null,
          status: null,
          useUnitId: null,
          useUnitName: null,
          books: []
        }
      }
    },
    computed: {
      columns() {
        const columns = []
        if (this.entity.status === null) {
          return []
        }
        columns.push(
          { prop: 'id', hide: true },
          { prop: 'bookId', hide: true },
          { label: '书籍名称', prop: 'name' },
          { label: '作者', prop: 'author' },
          { label: '编录号', prop: 'catalogCode' },
          { label: '图书编码', prop: 'bookCode' }
        )
        if (this.entity.status === 2) {
          columns.push({ label: '借阅时间', prop: 'borrowDateTime' }, { label: '归还时间', prop: 'returnDateTime' })
        }

        if (this.entity.status > 0) {
          columns.push({
            label: '状态',
            prop: 'status',
            align: 'center',
            options: bookBorrowStatus
          })
        }

        return columns
      }
    },
    methods: {
      create,
      load,
      save,
      update,
      async initEntity(id) {
        const entity = await this.loadEntity(id)
        entity.books = entity.books || []
        this.entity = entity
      },
      confirm(rows) {
        rows.forEach(value => {
          if (this.entity.books.findIndex(value1 => value1.bookId === value.id) === -1) {
            this.entity.books.push({
              id: null,
              bookApplyId: null,
              bookId: value.id,
              name: value.name,
              author: value.author,
              catalogCode: value.catalogCode,
              bookCode: value.bookCode,
              borrowDateTime: null,
              returnDateTime: null,
              status: null
            })
          }
        })
      },
      setUser(users) {
        const user = users[0]
        this.entity.useUnitId = user.deptId
        this.entity.useUnitName = user.deptName
      },
      async returnBook(row) {
        await returnBook([row.id])
        await this.initForm(this.entity.id)
        this.$message.success('归还成功!')
      },
      async beforeSend() {
        const res = await checkBooksStatus(this.entity.books.map(value => value.bookId))
        const ok = res.data.code === 0
        if (!ok) {
          this.$message.warning(`书籍[${res.data.data.map(value => value.name).join(',')}]已借出!`)
        }
        return ok
      }
    }
  }
</script>
